package com.minivision.migrate.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix="datasource.salmon")
@MapperScan(basePackages = {"com.minivision.migrate.mapper.salmon"}, sqlSessionFactoryRef = "salmonSqlSessionFactory")
public class SalmonDBConfig {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    @Bean(name="salmonDataSource")
    public DataSource salmonDataSource() {
        log.info("-------------------- salmonDataSource init ---------------------");
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName(driverClassName);
        return ds;
    }

    @Bean
    public SqlSessionFactory salmonSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(salmonDataSource());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/salmon/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate salmonSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(salmonSqlSessionFactory());
    }
}
